package com.engine.cube.cmd.restfulinterface;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.api.cube.service.CubeSearchService;
import com.api.cube.util.CubeCipherUitl;
import com.api.formmode.cache.*;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.cube.biz.CardHelper;
import com.engine.cube.biz.DataHelper;
import com.engine.cube.biz.ParamUtil;
import com.engine.cube.entity.CardEntity;
import com.engine.cube.util.InterfaceUtil;
import com.engine.hrm.biz.OrganizationShowSetBiz;
import com.weaver.formmodel.util.DateHelper;
import com.weaver.formmodel.util.StringHelper;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.crm.Maint.CustomerInfoComInfo;
import weaver.dateformat.DateTransformer;
import weaver.dateformat.TimeZoneVar;
import weaver.docs.docs.DocComInfo;
import weaver.docs.senddoc.DocReceiveUnitComInfo;
import weaver.formmode.data.ModeDataInterface;
import weaver.formmode.excel.ModeCacheManager;
import weaver.formmode.interfaces.OutsideInterfaceTransformationAction;
import weaver.formmode.log.FormmodeLog;
import weaver.formmode.search.FormModeTransMethod;
import weaver.formmode.setup.ModeRightInfo;
import weaver.formmode.tree.CustomTreeUtil;
import weaver.formmode.view.ModeViewLog;
import weaver.formmode.virtualform.VirtualFormHandler;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.workflow.browser.Browser;
import weaver.interfaces.workflow.browser.BrowserBean;
import weaver.proj.Maint.ProjectInfoComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.field.BrowserComInfo;
import weaver.workflow.request.ResourceConditionManager;
import weaver.workflow.workflow.WorkflowBillComInfo;
import weaver.workflow.workflow.WorkflowRequestComInfo;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class DeleteModeDataByPK extends AbstractCommonCommand<Map<String, Object>> {
    FormmodeLog logger = new FormmodeLog();
    InterfaceUtil interfaceUtil = null;
    int interfacetype = 1;
    String systemid = "";
    String interfacePK = "";
    String jsonString = "";
    String interfaceConfigId = "0";
    //int userLanguage = 7;//默认传入值为中文
    boolean isVirtualForm = false;
    String dataSource = "";
    String pkfieldname = "id";
    int vpkgentype = 0;
    String dtpkfieldname = "id";
    int feedbackLanguage = 7;
    String modeid = "";
    String formid = "";
    int isCheckRight = 0;
    String pkfield = "";

    public DeleteModeDataByPK(String interfacePK, Map<String, Object> params, User user){
        this.user = user;
        this.params = params;
        this.interfacePK = interfacePK;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String importdate = DateHelper.getCurrentDate();
        String importtime = DateHelper.getCurrentTime();
        try {
            interfaceUtil = new InterfaceUtil();
            this.jsonString = Util.null2String(this.params.get("datajson"));
            if(this.jsonString.length()==0){
                throw new Exception(SystemEnv.getHtmlLabelName(517560,this.feedbackLanguage));//"传入的参数datajson没有内容，请检查"
            }
            RecordSet rs = new RecordSet();
            RecordSet rs1 = new RecordSet();
            rs.executeQuery("select id from CubeInterfaceConfig where interfacePK=?",this.interfacePK);
            if(rs.next()){
                this.interfaceConfigId =  rs.getString("id");
            }
            if(Util.getIntValue( this.interfaceConfigId,0)==0){
                throw new Exception("BaseError:"+SystemEnv.getHtmlLabelName(502094,this.feedbackLanguage)+this.interfacePK+SystemEnv.getHtmlLabelName(517561,this.feedbackLanguage));//"BaseError:接口标识"+this.interfacePK+"找不到相关配置"
            }
            CubeInterfaceConfigComInfo cicci = new CubeInterfaceConfigComInfo();
            isCheckRight = Util.getIntValue(cicci.getIscheckRight(this.interfaceConfigId),0) ;
//            this.pkfield = cicci.getPkfield(this.interfaceConfigId);
//            if(this.pkfield.length()==0){
//                throw new Exception("没有设置主键字段");
//            }
            ModeComInfo modeComInfo = new ModeComInfo();
            this.modeid = cicci.getModeid(this.interfaceConfigId);
            this.formid = modeComInfo.getFormId(modeid);
            WorkflowBillComInfo wbc = new WorkflowBillComInfo();
            String maintablename = wbc.getTablename(formid);
            isVirtualForm = VirtualFormHandler.isVirtualForm(Util.getIntValue(this.formid));
            if(isVirtualForm) {
                ModeFormComInfo modeFormComInfo = new ModeFormComInfo();
                dataSource = modeFormComInfo.getVDataSource(this.formid);
                pkfieldname = modeFormComInfo.getVPrimaryKey(this.formid);
                //1： 32位ID (UUID)  2： 主键自动增长
                vpkgentype = Util.getIntValue(Util.null2String(modeFormComInfo.getvPkGenType(this.formid)), 0);
                maintablename = VirtualFormHandler.getRealFromName(maintablename);
            }

            int encryptionMode = Util.getIntValue(cicci.getEncryptionMode(this.interfaceConfigId));
            try {
                if (encryptionMode == 1) {//base64解密
                    this.jsonString = new String(weaver.general.Base64.decode(jsonString.getBytes("UTF-8")));
                } else if (encryptionMode == 2) {//其他加密方式
                    String path = cicci.getEncryptionPath(this.interfaceConfigId);
                    OutsideInterfaceTransformationAction action = (OutsideInterfaceTransformationAction) StaticObj.getServiceByFullname(path, OutsideInterfaceTransformationAction.class);
                    this.jsonString = action.importTransformation(this.jsonString);
                }
            }catch (Exception e){
                logger.writeLog(e);
                throw new Exception("BaseError:"+SystemEnv.getHtmlLabelName(517550,this.feedbackLanguage));//传入的json解密转换异常
            }
            JSONObject json = JSONObject.parseObject(jsonString);
            if(!json.containsKey("header")){
                throw new Exception("HeaderError:header"+SystemEnv.getHtmlLabelName(517551,this.feedbackLanguage));//节点未找到
            }
            JSONObject headerNode = json.getJSONObject("header");
            interfaceUtil = new InterfaceUtil(feedbackLanguage);
            this.checkHeaderNode(headerNode);
            if(!json.containsKey("operationinfo")){
                throw new Exception("OperatorError:operationinfo"+SystemEnv.getHtmlLabelName(517551,this.feedbackLanguage));
            }
            if(!json.containsKey("mainTable")){
                throw new Exception("mainTableError:mainTable"+SystemEnv.getHtmlLabelName(517551,this.feedbackLanguage));
            }

            JSONObject operationinfo = json.getJSONObject("operationinfo");
            String operatorStr = Util.null2String(operationinfo.getString("operator"));
            int createUserType = Util.getIntValue( cicci.getCreateUserType(this.interfaceConfigId),0);
            int operator = interfaceUtil.transformationUser(rs,createUserType,operatorStr);
            if(operator==0){
                throw new Exception("OperatorError:"+SystemEnv.getHtmlLabelName(517552,this.feedbackLanguage));//操作者未找到，或不是系统中的用户
            }
            JSONObject mainTableNode = json.getJSONObject("mainTable");
            JSONObject dataJson = new JSONObject();
            StringBuffer searchSqlwhere= new StringBuffer();
            List<Object> searchSqlwhereParam = new ArrayList<>();
            List<Map<String,String>> fieldArray = new ArrayList<>();
            String sql = "select d.fieldid,b.fieldname,b.fieldlabel,b.fielddbtype,b.fieldhtmltype,b.type,b.viewtype,b.qfws," +
                    "d.isRequired,d.isPK,d.valueType,d.tablename " +
                    " from CubeinterfaceConfigDetail d LEFT JOIN workflow_billfield b " +
                    "  on d.fieldid=b.id where d.mainid=? and isPK=1  order by d.tablename, d.isPK ";
            rs.executeQuery(sql,this.interfaceConfigId);
            boolean isParamError = true;
            while(rs.next()){
                String fieldid = Util.null2String(rs.getString("fieldid"));
                String fieldname = Util.null2String(rs.getString("fieldname"));
                String fieldlabel = Util.null2String(rs.getString("fieldlabel"));
                String fielddbtype = Util.null2String(rs.getString("fielddbtype"));
                String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype"));
                String type = Util.null2String(rs.getString("type"));
                //String viewtype = Util.null2String(rs.getString("viewtype"));
                String qfws = Util.null2String(rs.getString("qfws"));
                if(fieldid.equals("-1")){
                    fieldname = "id";
                    fieldlabel = "";
                    fielddbtype = "int";
                    fieldhtmltype = "1";
                    type = "1";
                    qfws = "0";
                }
                String isRequired = Util.null2String(rs.getString("isRequired"));
                String isPK = Util.null2String(rs.getString("isPK"));
                String valueType = Util.null2String(rs.getString("valueType"));
                String tablename1 = Util.null2String(rs.getString("tablename"));
                Map<String, String> fieldMap = new HashMap();
                fieldMap.put("fieldid", fieldid);
                fieldMap.put("fieldname", fieldname);
                fieldMap.put("fieldlabel", fieldlabel);
                fieldMap.put("fielddbtype", fielddbtype);
                fieldMap.put("fieldhtmltype", fieldhtmltype);
                fieldMap.put("type", type);
                fieldMap.put("qfws", qfws);
                fieldMap.put("isRequired", isRequired);
                fieldMap.put("isPK", isPK);
                fieldMap.put("valueType", valueType);
                fieldMap.put("tablename", tablename1);
                fieldArray.add(fieldMap);
                if(!mainTableNode.containsKey(fieldname)){
                    isParamError = false;
                }
                if("-1".equals(fieldid)){
                    int idvalue = Util.getIntValue( Util.null2String(mainTableNode.getString("id")),0);
                    searchSqlwhere.append(" and id="+idvalue);
                }else{
                    String fieldvalue = Util.null2String(mainTableNode.getString(fieldname));
                    String dbfieldvalue = interfaceUtil.checkAndTransformationFieldValue(rs1,fieldid,fieldname,fielddbtype,Util.getIntValue(fieldhtmltype,0),Util.getIntValue(type,0),qfws,isRequired,isPK,valueType,fieldvalue);
                    if(dbfieldvalue.length()!=0){
                        if(fielddbtype.startsWith("int") || fielddbtype.startsWith("float") || fielddbtype.startsWith("number") || fielddbtype.startsWith("decimal")){
                            searchSqlwhere.append(" and "+fieldname+"="+dbfieldvalue);
                        }else if((fielddbtype.equals("clob") || fielddbtype.equals("text"))||(fieldhtmltype.equals("2"))){
                            //mainTablePKSqlwhere = " and "+fieldname+" = ?";
                            searchSqlwhere.append(" and " +interfaceUtil.getTextCondition2(fieldname,dbfieldvalue,rs.getDBType()));
                            //searchSqlwhere.append(" and "+fieldname+"=?");
                            //searchSqlwhereParam.add(dbfieldvalue);
                        }else{
                            searchSqlwhere.append(" and "+fieldname+"='"+dbfieldvalue+"'");
                        }
                    }
                }
            }

            if(!isParamError){
                throw new Exception(SystemEnv.getHtmlLabelName(517553,this.feedbackLanguage));//"传入参数和配置的有主键字段不匹配，请查看配置"
            }
            RecordSet rssql = new RecordSet();
            sql = "select * from "+maintablename+" where "+(searchSqlwhere.toString().trim().substring(3));
            if(isVirtualForm){
                rssql.executeQueryWithDatasource(sql,this.dataSource,searchSqlwhereParam);
            }else{
                rssql.executeQuery(sql,searchSqlwhereParam);
            }
            String billid = "";
            if(rssql.getCounts()==0){
                dataJson.put("message",SystemEnv.getHtmlLabelName(517555,this.feedbackLanguage));//"找不到要删除的数据"
            }
            while(rssql.next()){
                billid = rssql.getString(pkfieldname);
                if(isCheckRight==1){

                    CardEntity card = new CardEntity();
                    card.setVirtualForm(isVirtualForm);
                    card.setType(0);
                    card.setModeId(Util.getIntValue(this.modeid));
                    card.setFormId(Util.getIntValue(this.formid));
                    Map<String,String> params = new HashMap<>();
                    params.put("pkfield",pkfieldname);
                    card.setParams(params);
                    card.setBillId(billid);
                    CardHelper.checkRight(card,new User(operator));
                    if(!card.isDel()){
                        throw new Exception(SystemEnv.getHtmlLabelName(517554,this.feedbackLanguage));//"该操作者对数据没有删除权限"
                    }
                }
                String operatetype = "3";
                String operatedesc = SystemEnv.getHtmlLabelName(520283,this.feedbackLanguage);//删除

                String isDoCardInterface = cicci.getDoCardInterface(this.interfaceConfigId);
                if("1".equals(isDoCardInterface)){
                    rs.executeQuery("select id from mode_pageexpand where issystem=1 and issystemflag=5 and modeid=" + this.modeid);
                    if (rs.next()) {
                        int pageexpandid = rs.getInt("id");
                        doInterface(billid, this.formid, this.modeid, operator, pageexpandid, new HashMap<>());
                    }
                }

                int htmllabelindex = 0;//#887673
                htmllabelindex = 520283;
                if(isVirtualForm) {
                    //DataHelper dataHelper = new DataHelper();
                    //dataHelper.doInterface(card, pageexpandid,param);
                    //String pageExpendResult = dataHelper.getPageExpendResult();
                    this.createDelData(modeid+"");
                    String deljsonString = this.getDeleteJson(formid,maintablename,billid);
                    String delsql = " delete from "+maintablename+" where "+(searchSqlwhere.toString().trim().substring(3));
                    boolean bool = rs.executeUpdateWithDatasource(delsql,dataSource);

                    ModeViewLog modeViewLog = new ModeViewLog();
                    modeViewLog.resetParameter();
                    modeViewLog.setClientaddress(ParamUtil.get(params, "param_ip"));
                    modeViewLog.setModeid(Util.getIntValue(this.modeid));
                    modeViewLog.setOperatedesc(operatedesc);
                    modeViewLog.setHtmllabelindex(htmllabelindex);
                    modeViewLog.setOperatetype(operatetype);
                    modeViewLog.setOperateuserid(operator);
                    modeViewLog.setRelatedid(Util.getIntValue(billid));
                    modeViewLog.setDeldata(deljsonString);
                    long s = modeViewLog.setSysLogInfo();
                    if(bool) {
                        dataJson.put("message", SystemEnv.getHtmlLabelName(20461,this.feedbackLanguage));//"删除成功"
                    }else{
                        dataJson.put("message",SystemEnv.getHtmlLabelName(20462,this.feedbackLanguage));//"删除失败"
                    }
                }else{
                    //rs.executeUpdate(" delete * from "+maintablename+" where id = ? ", billid);
                    this.createDelData(modeid+"");
                    String deljsonString = this.getDeleteJson(formid,maintablename,billid);
                    RecordSetTrans rst = new RecordSetTrans();
                    rst.setAutoCommit(false);
                    try {
                        rst.executeUpdate("delete from "+maintablename+" where id= ? ", billid);//删除主表数据
                        rs.executeQuery("select tablename from Workflow_billdetailtable where billid = ? ", this.formid); // 查询单据明细表的信息
                        while(rs.next()){
                            String deltablename = rs.getString("tablename");
                            rst.executeUpdate("delete from "+deltablename+" where mainid= ? ", billid);//删除明细
                        }
                        rst.executeUpdate("delete from modeDataShare_"+this.modeid+" where sourceid= ? ", billid);
                        rst.executeUpdate("delete from modeDataShare_"+this.modeid+"_set where sourceid=?", billid);
                        rst.commit();
                        ModeRightInfo modeRightInfo = new ModeRightInfo();

                        modeRightInfo.delDocShare(Util.getIntValue(this.modeid), Util.getIntValue(billid));

                        ModeViewLog modeViewLog = new ModeViewLog();
                        modeViewLog.resetParameter();
                        modeViewLog.setClientaddress(ParamUtil.get(params, "param_ip"));
                        modeViewLog.setModeid(Util.getIntValue(this.modeid));
                        modeViewLog.setOperatedesc(operatedesc);
                        modeViewLog.setHtmllabelindex(htmllabelindex);
                        modeViewLog.setOperatetype(operatetype);
                        modeViewLog.setOperateuserid(operator);
                        modeViewLog.setRelatedid(Util.getIntValue(billid));
                        modeViewLog.setDeldata(deljsonString);
                        modeViewLog.setSysLogInfo();
                        dataJson.put("message",SystemEnv.getHtmlLabelName(20461,this.feedbackLanguage));
                    } catch (Exception e) {
                        rst.rollback();
                        dataJson.put("message",SystemEnv.getHtmlLabelName(20462,this.feedbackLanguage));
                    }
                }
            }
            String resultJsonString = JSONObject.toJSONString(dataJson);
            if(encryptionMode==1){//base64解密
                resultJsonString = new String(weaver.general.Base64.encode(resultJsonString.getBytes("UTF-8")));
            }else if(encryptionMode==2){//其他解密方式
                String path = cicci.getEncryptionPath(this.interfaceConfigId);
                OutsideInterfaceTransformationAction action= (OutsideInterfaceTransformationAction) StaticObj.getServiceByFullname(path, OutsideInterfaceTransformationAction.class);
                resultJsonString = action.exportTransformation(resultJsonString);
            }
            resultMap.put("result",resultJsonString);
            resultMap.put("status","1");
        }catch (JSONException exception){
            exception.printStackTrace();
            logger.writeLog(exception);
            resultMap.put("status","4");
            resultMap.put("message",SystemEnv.getHtmlLabelName(517556,this.feedbackLanguage));//"json解析异常，请核查json格式"
        }catch (Exception e){
            e.printStackTrace();
            logger.writeLog(e);
            resultMap.put("status","4");
            resultMap.put("message",e.getMessage());
        }finally {
            //保存接口日志
            interfaceUtil.saveInterfaceLog(this.systemid,
                    Util.getIntValue(this.interfaceConfigId,4),
                    this.interfacetype,this.jsonString,JSONObject.toJSONString(resultMap),importdate,importtime);
        }

        return resultMap;
    }

    /**
     * 校验header参数
     * @param headerNode header json节点
     * @return  接口语音
     * @throws Exception
     */
    public void checkHeaderNode(JSONObject headerNode) throws Exception {
        Map<String,String> map =  interfaceUtil.checkHeaderNode(headerNode,this.interfaceConfigId);
        this.feedbackLanguage = Util.getIntValue(Util.null2String(map.get("feedbackLanguage")),7);
        this.systemid = Util.null2String(map.get("systemid"));
    }

    public void createDelData(String modeId){
        String modeviewlog = "modeviewlog_"+modeId;
        String sql = "select * from "+modeviewlog+" where id = 1 ";
        RecordSet rs =  new RecordSet();

        rs.executeQuery(sql);
        boolean isDelData = true;
        String[] colunms = rs.getColumnName();
        for(String column:colunms){
            if("deldata".equals(column.toLowerCase())){  //如果有deldata这个字段，那就不创建该字段。
                isDelData = false;
            }
        }
        if(isDelData){
            String dbType = rs.getDBType();
            String addDeleteDataSql = "";
            if(dbType.toLowerCase().startsWith("sqlserver")){
                addDeleteDataSql = "alter table "+modeviewlog+" add deldata text";
            }else if(dbType.toLowerCase().startsWith("mysql")){
                addDeleteDataSql = "alter table "+modeviewlog+" add deldata text";
            }
            else if(dbType.toLowerCase().startsWith("postgresql")){
                addDeleteDataSql = "alter table "+modeviewlog+" add deldata text";
            }
            else{
                addDeleteDataSql = "alter table "+modeviewlog+" add deldata clob";
            }
            rs.execute(addDeleteDataSql);
        }
    }

    public String getDeleteJson(String formId,String tablename,String billid){
        RecordSet rs =  new RecordSet();
        RecordSet dRs =  new RecordSet();
        String mainDataSql = "select * from "+tablename+" where id = ?";
        rs.executeQuery(mainDataSql,billid);
        Map<String,Object> deleteJson = new LinkedHashMap<String,Object>();   //json格式存数据库
        Map<String,String> mainTableData = new LinkedHashMap<String, String>();  //主表数据
        String[] mainColumn = rs.getColumnName();
        if(rs.next()){
            for(String column:mainColumn){
                mainTableData.put(column,rs.getString(column));
            }
            deleteJson.put(tablename,mainTableData);
        }
        rs.executeQuery("select id,tablename from Workflow_billdetailtable where billid = ? order by id asc",formId); // 查询单据明细表的信息
        while (rs.next()){
            List<Map<String,String>> detailDataList = new ArrayList<Map<String,String>>();
            String deltablename = rs.getString("tablename");
            dRs.executeQuery("select * from "+deltablename+" where mainid = ?",billid);
            String[] detailColumn = dRs.getColumnName();
            while(dRs.next()){
                Map<String,String> detailData = new LinkedHashMap<String, String>(); //明细表数据
                for(String column:detailColumn){
                    detailData.put(column,dRs.getString(column));
                }
                detailDataList.add(detailData);
            }
            deleteJson.put(deltablename,detailDataList);
        }
        JSONObject oJson = new JSONObject();
        oJson = new JSONObject(deleteJson);
        String jsontext =oJson.toString();
        return jsontext;
    }

    public void doInterface(String billid,String formid,String modeid,int userid, int pageexpandid,Map<String, Object> params){
        ModeDataInterface modeDataInterface = new ModeDataInterface();
        modeDataInterface.setBillid(billid);
        modeDataInterface.setFormid(Util.getIntValue(formid));
        modeDataInterface.setPageexpandid(pageexpandid);
        modeDataInterface.setModeid(Util.getIntValue(modeid));
        modeDataInterface.setUser(new User(userid));
        modeDataInterface.setParams(params);
        Map<String, String> execute = modeDataInterface.execute();
        //this.pageExpendResult=JSONObject.toJSONString(execute);
    }
}


